'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: cos_service.py
* @Time: 2025/9/25
* @All Rights Reserve By Brtc
'''
import hashlib
import os
import uuid
from dataclasses import dataclass
from datetime import datetime

from injector import inject
from qcloud_cos import CosS3Client, CosConfig
from werkzeug.datastructures import FileStorage

from internal.entity.upload_file_entity import ALLOWED_DOCUMENT_EXTENSION, ALLOWED_IMAGE_EXTENSION
from internal.exception.exception import FailException
from internal.model import UploadFile, Account
from .upload_file_service import UploadFileService


@inject
@dataclass
class CosService:
    upload_file_service:UploadFileService

    """腾讯云cos 对象存储服务"""
    def upload_file(self, file:FileStorage,  account:Account, only_image:bool=False)->UploadFile:
        """上传文件到腾讯云cos 服务, 上传后返回文件的信息"""
        #1、提取文件扩展名，并检测是否可以上传
        filename = file.filename
        extension = filename.rsplit(".",1)[-1] if "." in filename else ""
        if extension.lower() not in (ALLOWED_DOCUMENT_EXTENSION + ALLOWED_IMAGE_EXTENSION):
            raise FailException(f"该.{extension}扩展名文件不允许上传")
        elif only_image and extension not  in ALLOWED_IMAGE_EXTENSION:
            raise FailException(f"该.{extension}扩展名图片不允许上传")
        # 2、获取客户端+存储桶名字
        client = self._get_client()
        bucket = self._get_bucket()
        # 3、生成一个随机 名字
        random_filename = str(uuid.uuid4()) + "." + extension
        now = datetime.now()
        upload_file_name = f"{now.year}/{now.month:02d}/{now.day:02d}/{random_filename}"
        #4、流式读取上传的数据并上传到cos中
        file_content = file.stream.read()
        try:
            #5、将数据上传到存储桶中
            client.put_object(bucket,file_content, upload_file_name)
        except Exception as e:
            raise FailException("文件上传失败，请稍后再试！！")
        #6、闯将upload file记录
        return self.upload_file_service.create_upload_file(
            account_id = account.id,
            name = filename,
            key=upload_file_name,
            size = len(file_content),
            extension=extension,
            mime_type = file.mimetype,
            hash = hashlib.sha3_256(file_content).hexdigest()
        )


    @classmethod
    def get_file_url(cls, key:str)->str:
        """根据传递的cos云端key，获取图片的实际Url 地址"""
        cos_domain = os.getenv("COS_DOMAIN")
        if not cos_domain:
            bucket = os.getenv("COS_BUCKET")
            scheme = os.getenv("COS_SCHEME")
            region = os.getenv("COS_REGION")
            cos_domain = f"{scheme}://{bucket}.cos.{region}.myqcloud.com"
        return f"{cos_domain}/{key}"


    @classmethod
    def _get_client(cls)->CosS3Client:
        """获取腾讯云对象客户端"""
        conf = CosConfig(
            Region = os.getenv("COS_REGION"),
            SecretId = os.getenv("COS_SECRET_ID"),
            SecretKey = os.getenv("COS_SECRET_KEY"),
            Token = None,
            Scheme = os.getenv("COS_SCHEME", "https")
        )
        return CosS3Client(conf)


    def download_file(self, key:str, target_file_path:str):
        """下载cos云端文件到本地的指定路径"""
        client = self._get_client()
        bucket = self._get_bucket()

        client.download_file(bucket, key, target_file_path)


    @classmethod
    def _get_bucket(cls)->str:
        """获取存储桶名字"""
        return os.getenv("COS_BUCKET")


























